package com.rc.evcharger.job;

import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.utils.DateHelper;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.protocol.ylevcharger.netty.server.YLNettyPileHandler;
import com.rc.evcharger.protocol.ylevcharger.service.YlCommandService;
import com.rc.evcharger.service.elec.ElecGunService;
import com.rc.evcharger.service.elec.ElecPileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;

/**
 * yang
 * 2022/06/13
 */
public class TimingJob {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private YlCommandService commandService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ElecGunService elecGunService;

    /**
     * 定时下发对时指令,每15分钟就会下发
     */
    public void run() {
        YLNettyPileHandler nettyPileHandler = YLNettyPileHandler.newInstance();
        Map<String, String> rtuaMap = nettyPileHandler.getRtuaMap();

        for (String rtua : rtuaMap.keySet()) {
            ElecGun elecGun = elecGunService.selectGunBypileRtua(rtua);

            if (elecGun == null) {
//                nettyPileHandler.remove(rtua);
                continue;
            }

            int i = commandService.sendTimingDate(elecGun.getElecGunId());
            if (i == SocketConstant.FAIL) {
                logger.error("下发校时失败，对应桩编号:{}", elecGun.getGunNo());
                continue;
            }

            logger.info("下发校时成功，对应桩编号:{}", elecGun.getGunNo());
        }
    }

    /**
     * 将日期时间转为 ss mm HH dd MM yy格式字符串
     *
     * @return
     */
    private String getValue() {
//        Calendar c = Calendar.getInstance();
//        c.setTime(new Date());
//        String yy = String.valueOf(c.get(Calendar.YEAR)).substring(2);
//        String MM = DataUtil.coverPosition(String.valueOf(c.get(Calendar.MONTH) + 1));
//        String dd = DataUtil.coverPosition(String.valueOf(c.get(Calendar.DAY_OF_MONTH)));
//        String HH = DataUtil.coverPosition(String.valueOf(c.get(Calendar.HOUR_OF_DAY)));
//        String mm = DataUtil.coverPosition(String.valueOf(c.get(Calendar.MINUTE)));
//        String ss = DataUtil.coverPosition(String.valueOf(c.get(Calendar.SECOND)));
//
//        StringBuffer sb = new StringBuffer();
//        sb.append(ss).append(DataUtil.SPLIT).append(mm).append(DataUtil.SPLIT)
//                .append(HH).append(DataUtil.SPLIT).append(dd).append(DataUtil.SPLIT)
//                .append(MM).append(DataUtil.SPLIT).append(yy);
//        return sb.toString();
        String s = DateHelper.dataToString(new Date(), DateHelper.DATE_COMMON_FORMAT);
        return s;
    }

}
